package com.hongye.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.hongye.app.model.PaymentModel;
import com.hongye.app.model.ReturnGoodsModel;
import com.hongye.app.model.UserAppModel;
import com.hongye.util.Utils;
import com.jfinal.core.Controller;


public class PaymentController extends Controller{
//	private static String DocPath = "http://120.27.117.192/rbg/doc/";//下载路径
	private static String DocPath = "C:/MyPro/apache-tomcat-7.0.70/webapps/rbg/doc/";//下载路径
	public PaymentController() {
	}
	
	/**
	 * 管理端--获取交易列表
	 * @author lifuqiang
	 * 2016-12-20
	 */
	public void paymentView(){
		String sql = "select *, c_time as c_time from payment order by c_time desc";
		List<PaymentModel> paymentlist = PaymentModel.dao.find(sql);
		String[] ids = new String[paymentlist.size()];
		for (int i = 0; i < ids.length; i++) {
			int id = paymentlist.get(i).get("id");
			ids[i] = String.valueOf(id);
		}
		for(PaymentModel pay : paymentlist){
			pay.put("nick", UserAppModel.getById(pay.get("user_id").toString()).get("nick"));
		}
		this.setAttr("paymentlist", paymentlist);
		this.setAttr("ids", Arrays.toString(ids));
		this.renderJsp("paymentView.jsp");
	}
	
	/**
	 * 筛选交易信息列表
	 * @author lifuqiang
	 * 2016-12-20
	 */
	public void screen(){
		String startTime = this.getPara("startTime");
		String endTime = this.getPara("endTime");
		String state = this.getPara("state");
		List<PaymentModel> paymentlist = null;
		String time_start = null;
		String time_end = null;
		if(startTime.equals("")){
			startTime = "01/01/2017";
		}
		if(endTime.equals("")){
			time_end = Utils.getDate().toString();
		}else{
			time_end = Utils.sdfTosdf(endTime, "MM/dd/yyyy", "yyyy-MM-dd HH:mm:ss");
		}
		if(state == null){
			state = "0,1,2,3";
		}
		time_start = Utils.sdfTosdf(startTime, "MM/dd/yyyy", "yyyy-MM-dd HH:mm:ss");
		paymentlist = PaymentModel.dao.getPaymentByScreen(time_start,time_end,state);
		String[] ids = new String[paymentlist.size()];
		for (int i = 0; i < ids.length; i++) {
			int id = paymentlist.get(i).get("id");
			ids[i] = String.valueOf(id);
		}
		for(PaymentModel pay : paymentlist){
			pay.put("nick", UserAppModel.getById(pay.get("user_id").toString()).get("nick"));
		}
		this.setAttr("paymentlist", paymentlist);
		this.setAttr("ids", Arrays.toString(ids));
		this.renderJsp("paymentView.jsp");
	}
	
	/**
	 * 调用下载
	 * @author lifuqiang
	 * 2016-12-21
	 * @throws Exception 
	 */
	public void download(){
		String idstr = this.getPara("ids");
		String[] ids = idstr.substring(1, idstr.length()-1).split(", ");
		try {
			exportexcel(ids,this.getResponse());
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.renderNull();
	}
	
	/**
	 * 下载交易信息到Excel
	 * @author lifuqiang
	 * 2016-12-21
	 * @throws Exception 
	 */
	@SuppressWarnings("resource")
	public void exportexcel(String[] ids, HttpServletResponse response) throws Exception{
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("交易统计表.xls");//创建一个工作表aa.xls
		sheet.setColumnWidth(0, 3000);//设置列宽
		sheet.setColumnWidth(1, 5000);
		sheet.setColumnWidth(2, 8000);
		sheet.setColumnWidth(3, 5000);
		sheet.setColumnWidth(4, 8000);
		sheet.setColumnWidth(5, 5000);
		sheet.setColumnWidth(6, 5000);
		sheet.setColumnWidth(7, 5000);
		sheet.setColumnWidth(8, 5000);
		sheet.setColumnWidth(9, 5000);
		HSSFCellStyle style = wb.createCellStyle();//获取单元格样式对象
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置居中
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		
        HSSFRow row = sheet.createRow((int) 0); // 开始填充数据
		HSSFCell cellScore = null;
		String channel = null ;
		String state = null ;
		String type = null ;
		short colNum = 0;// 列起始
		cellScore = row.createCell(0);   //设置表头
		cellScore.setCellValue("序号");  
		cellScore.setCellStyle(style);  
		
		cellScore = row.createCell(1);  
		cellScore.setCellValue("收款/付款");  
		cellScore.setCellStyle(style);  
		
		cellScore = row.createCell(2);  
		cellScore.setCellValue("订单编号");  
		cellScore.setCellStyle(style);  
		
		cellScore = row.createCell(3);  
		cellScore.setCellValue("用户手机号");  
		cellScore.setCellStyle(style);  
		
		cellScore = row.createCell(4);  
        cellScore.setCellValue("交易渠道");  
        cellScore.setCellStyle(style);  
        
        cellScore = row.createCell(5);  
        cellScore.setCellValue("用户支付账号");  
        cellScore.setCellStyle(style); 
        
        cellScore = row.createCell(6);  
        cellScore.setCellValue("交易金额（元）");  
        cellScore.setCellStyle(style);  
        
        cellScore = row.createCell(7);  
        cellScore.setCellValue("创建时间");  
        cellScore.setCellStyle(style);  
        
        cellScore = row.createCell(8);  
        cellScore.setCellValue("成功时间");  
        cellScore.setCellStyle(style);  
        
		cellScore = row.createCell(9);  
        cellScore.setCellValue("失败时间");  
        cellScore.setCellStyle(style); 
        
		cellScore = row.createCell(10);  
        cellScore.setCellValue("支付状态");  
        cellScore.setCellStyle(style); 
		List<PaymentModel> list = new ArrayList<PaymentModel>();
		for (int i = 0; i < ids.length; i++) {
			list.add(PaymentModel.dao.findById(ids[i]));
		}
		for (int i = 0; i < list.size(); i++) {
			int nclo = colNum;
			row = sheet.createRow(i + 1);
			HSSFCell cell = row.createCell(0);
			cell.setCellValue(i+1);
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellScore.setCellValue(i);
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			if(0==list.get(i).getInt("type")){
				type = "收款";
			}else if (1==list.get(i).getInt("type")) {
				type = "付款";
			}
			cellScore.setCellValue(type);
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellScore.setCellValue(list.get(i).getStr("ordersn"));
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellScore.setCellValue(list.get(i).getStr("user_phone"));
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			if("alipay".equals(list.get(i).get("channel"))){
				channel = "支付宝";
			}else if("weixin".equals(list.get(i).get("channel"))){
				channel = "微信";
			}
			cellScore.setCellValue(channel);
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellScore.setCellValue(list.get(i).getStr("payment_account"));
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			BigDecimal bd= list.get(i).get("money");
			cellScore.setCellValue(bd.doubleValue());
			cellScore.setCellStyle(style);
			cellScore.setCellValue(channel);
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			cellScore.setCellValue(Utils.sdfToDate(list.get(i).get("c_time").toString(), sdf));
			HSSFCellStyle cellStyle = wb.createCellStyle();
            HSSFDataFormat format= wb.createDataFormat();
			cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置居中
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            cellStyle.setDataFormat(format.getFormat("yyyy/MM/dd HH:mm:ss"));
			cellScore.setCellStyle(cellStyle);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			Timestamp successtime = list.get(i).get("successtime");
			if(successtime==null){
				cellScore.setCellValue("");
			}else{
				cellScore.setCellValue(Utils.sdfToDate(list.get(i).get("successtime").toString(), sdf));
			}
			HSSFCellStyle cellStyle3 = wb.createCellStyle();
            HSSFDataFormat format3= wb.createDataFormat();
            cellStyle3.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置居中
            cellStyle3.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            cellStyle3.setDataFormat(format3.getFormat("yyyy/MM/dd HH:mm:ss"));
			cellScore.setCellStyle(cellStyle3);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			Timestamp failedtime = list.get(i).get("failedtime");
			if(failedtime==null){
				cellScore.setCellValue("");
			}else{
				cellScore.setCellValue((Utils.sdfToDate(list.get(i).get("failedtime").toString(), sdf)));
			}
			HSSFCellStyle cellStyle2 = wb.createCellStyle();
            HSSFDataFormat format2= wb.createDataFormat();
            cellStyle2.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置居中
            cellStyle2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            cellStyle2.setDataFormat(format2.getFormat("yyyy/MM/dd HH:mm:ss"));
			cellScore.setCellStyle(cellStyle2);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			if(0==list.get(i).getInt("state")){
				state = "申请支付";
			}else if(1==list.get(i).getInt("state")){
				state = "支付取消";
			}else if(2==list.get(i).getInt("state")){
				state = "支付成功";
			}
			cellScore.setCellValue(state);
			cellScore.setCellStyle(style);
		}
		
		String fileName = "交易统计信息表.xls";
		String myExcel = DocPath;
//		String myExcel = "E:/";
		String filePath = myExcel + fileName;
		FileOutputStream out = new FileOutputStream(filePath);// 创建xls文件
		wb.write(out);
		out.close();
		File file = new File(filePath);
		Utils.download(response, file, fileName);
	}
	
	/**
	 * 交易详情
	 * @author lifuqiang
	 * 2017-3-9
	 */
	public void paymentDetail(){
		String id = this.getPara("paymentid");
		String sql = "select * from payment where id = "+id+"";
		PaymentModel payment = PaymentModel.dao.findFirst(sql);
		String sql2 = "select * from return_g where g_order = '"+payment.get("ordersn")+"'";
		ReturnGoodsModel returngoods = ReturnGoodsModel.dao.findFirst(sql2);
		this.setAttr("payment", payment);
		this.setAttr("returngoods", returngoods);
		this.renderJsp("paymentDetail.jsp");
	}
}
